<!DOCTYPE html>
<html>
  <head>
    <title>Tilt handler - Leaflet</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>

    <style>
      html,
      body {
        height: 100%;
        margin: 0;
      }
      #map {
        width: 600px;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>

    <style>
      #info {
        position: absolute;
        top: 0;
        right: 0;
        width: 20em;
        height: 7.5em;
        background: rgba(255, 255, 255, 0.5);
        z-index: 500;
        font: 12px Sans;
      }
    </style>

    <div id="info"></div>

    <script type="text/javascript">
      L.TiltHandler = L.Handler.extend({
        addHooks: function () {
          L.DomEvent.on(window, 'deviceorientation', this._tilt, this)
        },

        removeHooks: function () {
          L.DomEvent.off(window, 'deviceorientation', this._tilt, this)
        },

        _tilt: function (ev) {
          // Treat Gamma angle as horizontal pan (1 degree = 1 pixel) and Beta angle as vertical pan
          var info
          var offset = L.point(ev.gamma, ev.beta)
          if (offset) {
            // 平移地图
            this._map.panBy(offset)
            info = ev.gamma + ',' + ev.beta
          } else {
            info = 'Device orientation not detected'
          }
          document.getElementById('info').innerHTML = info
        }
      })

      // 所有地图实例都添加事件处理程序
      L.Map.addInitHook('addHandler', 'tilt', L.TiltHandler)

      var map = L.map('map', {
        center: [0, 0],
        zoom: 1,
        tilt: true // 默认启用事件处理程序
      })

      // 在地图实例添加事件处理程序
      map.addHandler('tilt', L.TiltHandler)
      // 启用事件
      map.tilt.enable()
      // 禁用事件
      map.tilt.disable()

      var positron = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/attribution">CARTO</a>'
      }).addTo(map)
    </script>
  </body>
</html>
